<template>
  <!-- 冷铁需求详情表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="80%"
    draggable
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :inline="true"
      :rules="rules"
      label-width="80"
    >
      <el-row>
        <el-col :span="4">
          <el-form-item label="结束时间" prop="planActualDate">
            <el-date-picker
              v-model="formData.planActualDate"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择日期"
              @change="changePlanBeginTime"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-card shadow="never" class="table-container">
        <div class="formTable2">
          <el-table
            max-height="710"
            :data="formData.details"
            :key="Math.random"
            border
            style="width: 100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="80"
            />
            <el-table-column
              label="计划编号"
              prop="processingOrderNumber"
              min-width="180"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品图号"
              prop="figureNumber"
              min-width="170"
              show-overflow-tooltip
            />
            <el-table-column
              label="产品名称"
              prop="materialName"
              min-width="180"
              show-overflow-tooltip
            >
              <template #default="scope">
                {{ scope.row.materialName }}
              </template>
            </el-table-column>
            <el-table-column
              label="生产日期"
              prop="planActualDate"
              min-width="100"
              show-overflow-tooltip
              align="center"
              :formatter="formatDate"
            />
            <el-table-column
              label="外协类型"
              prop="processesClassification"
              min-width="130"
              align="center"
            >
              <template #default="scope">
                <span v-if="scope.row.processesClassification === 12"
                  >外协(打磨)</span
                >
                <span v-if="scope.row.processesClassification === 16"
                  >外协(抛光打磨)</span
                >
              </template>
            </el-table-column>
            <el-table-column
              label="供应商"
              prop="processesClassification"
              min-width="100"
              align="center"
            />
            <el-table-column
              label="计划数量"
              prop="planQuantity"
              min-width="100"
              show-overflow-tooltip
              header-align="center"
              align="right"
            />
            <el-table-column
              label="生产批次号"
              prop="plannedBatch"
              min-width="100"
              show-overflow-tooltip
            />
            <el-table-column
              label="上工序完成时间"
              prop="lastProcessFinshTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
            <!--<el-table-column label="计划人员" props="planUsers" min-width="180">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planUserIds'"
                  :rules="rules.sonplanUserIds"
                  label-width="0"
                  style="width: 100%"
                >
                  <el-select
                    v-model="row.memberIds"
                    placeholder="请选择计划人员"
                    clearable
                    style="width: 100%"
                    @change="changePlanUser(row)"
                    filterable
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    :max-collapse-tags="1"
                  >
                    <el-option
                      v-for="item in memberList"
                      :key="item.id"
                      :label="`${item.memberName}`"
                      :value="item.memberId"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>-->
            <el-table-column
              label="计划开始时间"
              prop="planBeginTime"
              min-width="210"
              align="center"
            >
              <!--<template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.planBeginTime'"
                  :rules="rules.sonplanBeginTime"
                  label-width="0"
                >
                  <el-date-picker
                    v-model="row.planBeginTime"
                    type="datetime"
                    placeholder="请选择开始时间"
                    format="YYYY-MM-DD HH:mm:ss"
                    @change="queryTimeEndOne(row)"
                  />
                </el-form-item>
              </template>-->
            </el-table-column>
            <el-table-column
              label="计划结束时间"
              prop="planEndTime"
              min-width="160"
              show-overflow-tooltip
              align="center"
            />
          </el-table>
        </div>
      </el-card>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit"
          >保 存</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "TIMEFILL",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  isPm: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    // setTimeout(() => {
    //   formRef.value.clearValidate();
    // }, 50);
    getPlanWorkingForm();
  }
);

const rules = reactive({
  sonplanUserIds: [
    { required: true, message: "请输入计划人员", trigger: "change" },
  ],
  sonplanBeginTime: [
    { required: true, message: "请选择计划开始时间", trigger: "change" },
  ],
  startTime: [],
  planActualDate: [
    { required: true, message: "请选择计划日期", trigger: "change" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  details: [],
  crewId: "",
  crewName: "",
  startTime: "",
  planActualDate: "",
});

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}
/**
 * 行checkbox change事件
 *
 * @param selection
 */
const rows = ref([]);
const handleSelectionChange = (selection: any) => {
  if (selection.length > 0 && formData.planActualDate) {
    selection.sort((a, b) => a.index - b.index);
    const t1 = new Date(
      selection[selection.length - 1].lastProcessFinshTime
    ).getTime();
    const t2 = new Date(formData.planActualDate).getTime();
    if (Math.sign(t1 - t2) > 0) {
      formData.planActualDate =
        selection[selection.length - 1].lastProcessFinshTime;
    }
  }
  rows.value = selection;
};
/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.crewId = "";
  formData.crewName = "";
  rows.value = [];
}

const loading = ref(false);

function handleSubmit() {
  // if (rows.value.length === 0) {
  //   ElMessage.error("请选择要填报的数据");
  //   return;
  // }
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      ElMessageBox.confirm("确实是否对已选数据进行时间填报?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        loading.value = true;
        const text = "时间填报";
        await request({
          url: "/mes/mesplanworkingform/saveOutsourcing",
          method: "post",
          data: {
            listWorkingForm: rows.value,
            planDate: formData.planActualDate,
          },
        }).finally(() => {
          loading.value = false;
        });
        ElMessage.success(text + `成功`);
        closeDialog();
        emit("reset-table", formData);
      });
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

//时间格式处理，yyyy-mm-dd
function formatDate(row, column) {
  const date = row[column.property];
  if (!date) return "";
  return date.split(" ")[0]; // 返回日期的年月日部分，而隐藏时间部分
}
// 获取当前日期yyyymmdd
function getCurrentDate() {
  const today = new Date();
  let year = today.getFullYear();
  let month = (today.getMonth() + 1).toString().padStart(2, "0");
  let day = today.getDate().toString().padStart(2, "0");
  return year.toString() + "-" + month + "-" + day;
}
async function getPlanWorkingForm() {
  // if (!formData.planActualDate) {
  //   ElMessage.error("请选择日期");
  //   return;
  // }
  request({
    url: `/mes/mesplanworkingform/queryByList`,
    method: "post",
    data: {
      processesClassifications: props.data.processesClassifications,
      queryByType: 2,
      isASC: 1,
    },
  })
    .then((res) => {
      res.data.forEach((item, index) => {
        item.index = index;
      });
      formData.details = res.data;
    })
    .catch((res) => {
      console.log(res);
    });
}
function changePlanBeginTime() {
  if (formData.planActualDate && rows.value.length > 0) {
    const t1 = new Date(
      rows.value[rows.value.length - 1].lastProcessFinshTime
    ).getTime();
    const t2 = new Date(formData.planActualDate).getTime();
    if (Math.sign(t1 - t2) > 0) {
      formData.planActualDate =
        rows.value[rows.value.length - 1].lastProcessFinshTime;
    }
  }
}
function calculateDuration(beginTime, time) {
  const start = new Date(beginTime);
  // let number = Math.round(time / 60) * 60 * 1000;
  let number = time * 1000;
  const extendedDate = new Date(start.valueOf() + number);
  const year = extendedDate.getFullYear();
  const month = String(extendedDate.getMonth() + 1).padStart(2, "0");
  const day = String(extendedDate.getDate()).padStart(2, "0");
  const hours = String(extendedDate.getHours()).padStart(2, "0");
  const minutes = String(extendedDate.getMinutes()).padStart(2, "0");
  const seconds = String(extendedDate.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
</script>
<style lang="scss" scoped>
.sketch_content {
  // 必须有高度 overflow 为自动
  overflow: auto;
  height: 750px;
}

// 滚动条的样式,宽高分别对应横竖滚动条的尺寸
.sketch_content::-webkit-scrollbar {
  width: 3px;
}

// 滚动条里面默认的小方块,自定义样式
.sketch_content::-webkit-scrollbar-thumb {
  background: #8798af;
  border-radius: 2px;
}

// 滚动条里面的轨道
.sketch_content::-webkit-scrollbar-track {
  background: transparent;
}
</style>
